package com.loong.android.http.request;

import com.loong.android.http.RequestEvent;
import com.loong.android.http.response.StringResponse;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okgo.request.base.Request;

/**
 * get请求类
 */
public class StringGetRequest extends GetRequest<String> {

    /**
     * 构造函数
     * @param url 请求的URL地址
     */
    public StringGetRequest(String url) {
        super(url);
    }

    /**
     * 创建并返回一个StringCallback实例，用于处理网络请求的回调
     * @param callback 请求事件回调接口
     * @return StringCallback实例
     */
    private StringCallback listen(final RequestEvent.GetEvent callback) {
        final StringGetRequest req = this;
        return new StringCallback() {
            @Override
            public void onStart(Request<String, ? extends Request> request) {
                super.onStart(request);
                if(callback != null) callback.onStart(req);
            }

            @Override
            public void onSuccess(Response<String> response) {
                if(callback != null) callback.onSuccess(new StringResponse(response));
            }

            @Override
            public void onCacheSuccess(Response<String> response) {
                super.onCacheSuccess(response);
                if(callback != null) callback.onCacheSuccess(new StringResponse(response));
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                if(callback != null) callback.onError(new StringResponse(response));
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if(callback != null) callback.onFinish();
            }
        };
    }

    /**
     * 设置事件回调
     * @param callback 事件回调
     */
    public StringGetRequest setCallback(RequestEvent.GetEvent callback) {
        super.setCallback(listen(callback));
        return this;
    }

    /**
     * 提交请求
     * @param callback 事件回调
     */
    public StringGetRequest execute(RequestEvent.GetEvent callback) {
        super.execute(listen(callback));
        return this;
    }


}

